const express = require( 'express' );
const bodyParse = require( 'body-parser' );
const app = express();

const models = require( './db/models' );

const Sequelize = require('sequelize');

app.use( express.json() );

// for parsing application/www-form-urlencoded
// app.use( express.urlencoded() );

// for parsing application/www-form-urlencoded
app.use( bodyParse.urlencoded({ extended: true }));

// 1. 所有的错误 http status == 500


// 创建一个 todolist
app.post( '/create', async ( req, res, next ) => {
  const { name, deadline, content } = req.body;
  try{
    let todo = await models.Todo.create({
      name,
      deadline,
      content
    });
    res.json({
      code: 200,
      message: '创建成功'
    });
  }catch(error){
    next( error )
  }
});

// 修改
app.post( '/update', async ( req, res, next ) => {
  const { id, name, content, deadline } = req.body;

  // const values = Object.values( req.body );

  // if( values.every( item => item ) ){
  //   next({
  //     message: '参数错误'
  //   });
  // }

  try {

    let todo = await models.Todo.findOne({
      where: { id }
    });

  // todo.dataValues
    if( todo ){
      todo = await todo.update({ 
        name, 
        deadline: deadline && new Date( deadline ), 
        content 
      });
      res.json({ code: 200, message: '更新成功' });
    }else{
      res.json({ code: 201, message: `任务不存在` })
    }

    
  }catch( e ){
    next( e )
  }
});

// 删除某一条数据
app.post( '/delete', async ( req, res, next ) => {
  let { id } = req.body;
  try {
    let todo = await models.Todo.destroy({
      where: { id }
    });
    res.json({ code: 200, message: '删除成功' });
  }catch( e ){
    next( e )
  }
});

// 更新状态
app.post( '/updateStatus', async ( req, res, next ) => {
  const { id, status } = req.body;
  try {

    let todo = await models.Todo.findOne({
      where: { id }
    });

    if( todo ){
      if( status != todo.status ){
        todo = await todo.update({ status });
      }
      res.json({ code: 200, message: '更新成功' });
    }else{
      res.json({ code: 201, message: `任务不存在` })
    }
  }catch( e ){
    next( e )
  }
});


// 查询列表
app.post( '/list', async ( req, res, next ) => {
  let { status, page=1 } = req.body;
  let limit = 10; // 每页数量
  let offset = ( page - 1 ) * limit;
  let where = {};

  if( status ){
    where.status = status;
  }
  // 执行查询后直接返回查询后的结果， 不在具有 sequelize 能力
  let todo = await models.Todo.findAndCountAll({
    where,
    offset,
    limit,
    attributes: { exclude: [ 'status', 'content' ] }
  });
  todo.list = todo.rows;
  delete todo.rows;

  res.json({
    data: { ...todo },
    code: 200,
    message: '查询成功',
  });

});

app.get( '/all', async ( req, res, next ) => {

  let all = await models.Todo.findAll({
    attributes: [ 
      'content', 'name', 'status', 'id', 'deadline',
      // [ models.sequelize.fn( 'COUNT', models.sequelize.col('content') ), 'contents' ] 
    ]
  });

  res.json({
    data: {
      ...all
    },
    code: 200,
    message: '查询成功'
  });

});


app.use( ( err, req, res, next ) => {
  if( err ){
    res.status( 500 ).json({
      code: 500,
      message: err.message,
    })
  }
});

app.listen( 3000, () => {
  console.log( 'service starting ...' );
}); 
